<template>
  <el-drawer v-model="dialogVisible" with-header="true" :size="type ? 550 : 820">
    <template #header>
      <div style="margin-bottom: 0px"
        >{{ drawerType ? '新增站点' : '编辑站点' }}
        <br />
        <br />
        <el-segmented v-if="!drawerType" v-model="type" :options="options" />
      </div>
    </template>
    <div v-if="type" style="margin-top: -20px">
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="150px"
        class="demo-ruleForm2"
      >
        <el-form-item label="站点名称：" prop="siteName">
          <el-input v-model="ruleForm.siteName" placeholder="请输入站点名称" />
        </el-form-item>
        <el-form-item label="所属小区：" prop="communityId">
          <el-select
            v-model="ruleForm.communityId"
            placeholder="请选择所属小区"
            style="width: 100%"
            filterable
            :disabled="disable"
          >
            <el-option
              v-for="ite in communityList"
              :key="ite.id"
              :label="ite.communityName"
              :value="ite.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="地址：" prop="siteAddress">
          <el-input v-model="ruleForm.siteAddress" placeholder="请输入地址" />
        </el-form-item>
        <div style="display: flex">
          <el-form-item label="插座数量：" prop="number">
            <el-input type="number" v-model="ruleForm.number" placeholder="请输入插座数量" />
          </el-form-item>
          <el-form-item label="电价(元/千瓦时)：" prop="price">
            <el-input
              type="number"
              v-model="ruleForm.price"
              placeholder="请输入电价"
              :disabled="!drawerType"
            />
          </el-form-item>
        </div>
        <div style="display: flex">
          <el-form-item label="电费分成比例(%)：" prop="feeRate">
            <el-input
              type="number"
              v-model="ruleForm.feeRate"
              placeholder="请输入电费分成比例"
              :disabled="!drawerType"
            />
          </el-form-item>
          <el-form-item label="收入分成比例(%)：" prop="incomeRate">
            <el-input
              type="number"
              v-model="ruleForm.incomeRate"
              placeholder="请输入收入分成比例"
              :disabled="!drawerType"
            />
          </el-form-item>
        </div>
        <el-form-item label="抄表类别：" prop="type">
          <el-select
            v-model="ruleForm.type"
            placeholder="请选择抄表类别"
            style="width: 100%"
            filterable
            :disabled="!drawerType"
          >
            <el-option
              v-for="ite in typeList"
              :key="ite.label"
              :label="ite.label"
              :value="ite.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="联系人信息：" prop="chargeInfo">
          <el-autocomplete
            v-model="ruleForm.chargeInfo"
            :fetch-suggestions="querySearch"
            :trigger-on-focus="true"
            clearable
            placeholder="请输入联系人信息"
            style="width: 100%"
            maxlength="64"
          />
        </el-form-item>
        <div style="display: flex">
          <el-form-item label="设立时间：" prop="createTime">
            <el-date-picker
              v-model="ruleForm.createTime"
              type="date"
              placeholder="请选择设立时间"
              format="YYYY/MM/DD"
              value-format="YYYY-MM-DD"
              style="width: 150px"
            />
          </el-form-item>
          <el-form-item label="状态：" v-if="!drawerType">
            <el-switch
              inline-prompt
              active-text="启用"
              inactive-text="禁用"
              v-model="ruleForm.status"
            />
          </el-form-item>
        </div>
        <el-form-item label="备注：" prop="remark">
          <el-input v-model="ruleForm.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
    </div>
    <div v-if="!type" style="margin-top: -20px">
      <div style="display: flex; justify-content: end">
        <el-button type="primary" @click="changeInfo">新增变更</el-button>
      </div>
      <el-table :data="memoryData">
        <el-table-column type="index" width="50" />
        <el-table-column property="price" label="电价(元/千瓦时)" width="130px">
          <template #default="scope">
            {{ scope.row.price }} —> {{ scope.row.updatePrice }}
          </template>
        </el-table-column>
        <el-table-column property="feeRate" label="电费分成比例(%)" width="140px">
          <template #default="scope">
            {{ scope.row.feeRate }} —> {{ scope.row.updateFeeRate }}
          </template>
        </el-table-column>
        <el-table-column property="incomeRate" label="收入分成比例(%)" width="140px">
          <template #default="scope">
            {{ scope.row.incomeRate }} —> {{ scope.row.updateIncomeRate }}
          </template>
        </el-table-column>
        <el-table-column property="type" label="抄表类别" width="200px">
          <template #default="scope"> {{ scope.row.type }} —> {{ scope.row.updateType }} </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="修改时间" width="120px"></el-table-column>
      </el-table>
    </div>
    <ChangeInfoDrawer ref="changeInfoRef" @getData="reset"></ChangeInfoDrawer>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submit(ruleFormRef)">确定</el-button>
      </span>
    </template>
  </el-drawer>
</template>

<script lang="ts" setup>
  import { ref, reactive, nextTick, inject } from 'vue'
  import type { FormInstance } from 'element-plus'
  import { postCommunityMatch } from '@/api/controller/community-controller/index'
  import { postSiteGetChargeInfo, getSiteById } from '@/api/controller/site-controller/index'
  import ChangeInfoDrawer from './changeInfo.vue'
  import {
    postSiteCreate,
    putSiteUpdate,
    getSiteUpdateListBySiteId,
    putSiteUpdateMoney,
  } from '@/api/controller/site-controller/index'
  import { ElMessage } from 'element-plus'
  const ruleFormRef = ref<FormInstance>()
  const changeInfoRef = ref()
  const drawerType = ref(true)
  const communityList = ref([])
  const typeList = ref([
    { value: '抄表计', label: '抄表计' },
    { value: '数据导入计', label: '数据导入计' },
  ])
  const type = ref(true)
  const options = [
    { label: '基本信息', value: true },
    { label: '变更记录', value: false },
  ]
  const ruleForm = ref({
    communityId: null,
    siteName: null,
    siteAddress: null,
    number: null,
    price: null,
    feeRate: null,
    incomeRate: null,
    status: false,
    type: null,
    feeIn: null,
    remark: null,
    createTime: null,
    chargeInfo: '',
  })

  const rules = reactive({
    communityId: [{ required: true, message: '请选择所属小区', trigger: 'blur' }],
    siteName: [
      { required: true, message: '请输入站点名称', trigger: 'blur' },
      { min: 0, max: 64, message: '长度不超过64个字符', trigger: 'blur' },
    ],
    siteAddress: [{ min: 0, max: 64, message: '长度不超过64个字符', trigger: 'blur' }],
    number: [
      { required: true, message: '请输入插座数量', trigger: 'blur' },
      {
        pattern: /^[0-9]*$/,
        message: '请输入大于或等于0的整数',
      },
    ],
    price: [
      { required: true, message: '请输入电价', trigger: 'blur' },
      {
        pattern: /^\d+(\.\d{1,2})?$/,
        message: '请输入大于或等于0的数字(最多2位小数)',
      },
    ],
    createTime: [{ required: true, message: '请输入设立时间', trigger: 'blur' }],
    feeRate: [
      { required: true, message: '请输入电费分成比例', trigger: 'blur' },
      {
        pattern: /^(([1-9]?\d{0,1}(\.\d{1,2})?)|100|100\.(0){1,2})$/,
        message: '请输入0-100内的数字(最多2位小数)',
      },
    ],
    incomeRate: [
      { required: true, message: '请输入收入分成比例', trigger: 'blur' },
      {
        pattern: /^(([1-9]?\d{0,1}(\.\d{1,2})?)|100|100\.(0){1,2})$/,
        message: '请输入0-100内的数字(最多2位小数)',
      },
    ],
    type: [
      { required: true, message: '请输入抄表类别', trigger: 'blur' },
      { min: 0, max: 64, message: '长度不超过64个字符', trigger: 'blur' },
    ],
    chargeInfo: [
      { required: true, message: '请输入联系人信息', trigger: 'blur' },
      { min: 0, max: 64, message: '长度不超过64个字符', trigger: 'blur' },
    ],
    remark: [{ min: 0, max: 64, message: '长度不超过64个字符', trigger: 'blur' }],
  })
  const dialogVisible = ref(false)
  //是否展示抄表记录
  const showMeterRecord = inject('showMeterRecord', () => {
    //
  })
  //新增或修改
  const submit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate(async (valid) => {
      if (valid) {
        let a = JSON.parse(JSON.stringify(ruleForm.value))
        if (a.chargeInfo === '空') {
          a.chargeInfo = null
        }
        if (drawerType.value) {
          const result = await postSiteCreate(a, { loading: true })
          if (result.code === 200) {
            dialogVisible.value = false
            await emit('getData')
            ElMessage.success('添加成功')
          }
        } else {
          let result = await putSiteUpdate(a, { loading: true })
          const { id, price, feeRate, incomeRate, type } = a
          result = await putSiteUpdateMoney(
            { id, price, feeRate, incomeRate, type },
            { loading: true },
          )
          if (result.code === 200) {
            dialogVisible.value = false
            await emit('getData')
            ElMessage.success('修改成功')
            showMeterRecord()
          }
        }
      } else {
        ElMessage.warning('请正确填写表单')
        return false
      }
    })
  }
  const memoryData = ref([])
  const disable = ref(false)
  const nowSiteId = ref(null)
  const show = (data, comId) => {
    postCommunityMatch({}).then((res) => {
      communityList.value = res.data
    })
    postSiteGetChargeInfo({}).then((res) => {
      restaurants.value = res.data.map((item) => {
        if (!item) {
          return { value: '空' }
        }
        return { value: item }
      })
    })
    if (data) {
      nowSiteId.value = data.id
      getSiteUpdateListBySiteId({ siteId: data.id }).then((res) => {
        memoryData.value = res.data
      })
      ruleForm.value = JSON.parse(JSON.stringify(data))
      if (!ruleForm.value.chargeInfo) {
        ruleForm.value.chargeInfo = ''
      }
      drawerType.value = false
    } else {
      drawerType.value = true
      ruleForm.value = {
        communityId: null,
        siteName: null,
        siteAddress: null,
        number: null,
        price: null,
        feeRate: null,
        incomeRate: null,
        status: false,
        type: null,
        feeIn: null,
        remark: null,
        createTime: null,
        chargeInfo: '',
      }
      if (comId) {
        ruleForm.value.communityId = comId
        disable.value = true
      } else {
        disable.value = false
      }
    }
    dialogVisible.value = true
    nextTick(() => {
      ruleFormRef.value.clearValidate()
    })
  }
  const changeInfo = () => {
    changeInfoRef.value.show(ruleForm.value)
  }
  const reset = () => {
    getSiteUpdateListBySiteId({ siteId: nowSiteId.value }).then((res) => {
      memoryData.value = res.data
    })
    getSiteById({ id: nowSiteId.value }).then((res) => {
      ruleForm.value = res.data
    })
  }
  const restaurants = ref([])
  const querySearch = (queryString: string, cb: any) => {
    const results = queryString
      ? restaurants.value.filter((item) => item.value.indexOf(queryString) >= 0)
      : restaurants.value
    // call callback function to return suggestions
    cb(results)
  }

  const emit = defineEmits(['getData'])
  defineExpose({
    show,
  })
</script>
